$(function () {
    var appExplorer = null;
    var containerWidth = 226;
    var $treeSortPanel = $('#tempo-tree-sort');
    var themeTreeSort = 'DEFAULT';
    var $searchBar = $(".tempo-app-rsmanage-search-bar");

    var indexOpts = $(".tempo-app-index-view");
    var contentOpts = $(".tempo-app-content-view");
    var $rightTaskView = $(".tempo-app-task-view");
    var indexOpts_addApp = $("#tempo-app-index-view-opts-addApp");
    var indexOpts_addFolder = $("#tempo-app-index-view-opts-addFolder");

    //灰度服务-右侧页面
    var $rightGrayView = $(".tempo-app-content-view-gray");
    // 调整目录
    var $selectBtn = $('.select_target-btn');

    $('body').layout({
        west: {
            size: containerWidth,
            resizable: false,
            spacing_open: 0,
            closable: false
        },
        center: {}
    });
    $searchBar.searchbar({
        width: 196,
        isEnter: true,
        placeholder: TempoUtils.locale("aiview.rsmanageSearch"),
        onSearch: function (text) {
            initExplorer(text);
            disableBtn();
        }
    });

    /**
     * 筛选后隐藏添加成果/新建文件夹
     * @param text
     */
    var disableBtn = function () {
        indexOpts_addApp.addClass('ui-state-disabled');
        indexOpts_addFolder.addClass('ui-state-disabled');
    }

    var bindIndexEvents = function () {
        //添加成果
        indexOpts_addApp.on("click", function () {
            if ($(this).hasClass('ui-state-disabled')) {
                return;
            }
            //通过iframe将服务详情页面加载过来
            var data = appExplorer.gtree("getSelected");
            $m.loadHtml(contextPath + "/api/ai/app/view/add-achievement", $('body'), 'tempo-app-add-achievement-dialog', {
                callback: addApp,
                parentId: data.id
            });
        });
        //添加文件夹
        indexOpts_addFolder.on("click", function () {
            if ($(this).hasClass('ui-state-disabled')) {
                return;
            }
            var data = appExplorer.gtree("getSelected");
            meunEvent.createFolder(data);
        });
        //创建任务
        var $createTaskBtn = $('.create-task-btn');
        $createTaskBtn.button({
            emphasize: true,
            click: function (e) {
                var data = appExplorer.gtree("getSelected");
                createTask(data);
            }
        });
        //删除任务
        var $deleteTaskBtn = $('.delete-task-btn');
        $deleteTaskBtn.button({
            emphasize: true,
            click: function (e) {
                var data = appExplorer.gtree("getSelected");
                // deleteTask(data);
            }
        });
        // 更新树上服务的名称
        Eventbus.one('updateName.service', function (row) {
            if (row && row.id && row.name) {
                appExplorer.gtree("updateItemName", row.id, row.name);
                $('#ca-name').text(row.name);
            }
        });
        Eventbus.bind("updateserviceStatus.service", function (status, id) {
            $('div[objid="' + id + '"] #ca-status').text(status);
            $('div[objid="' + id + '"] #service_status').text(status);
        });

        $selectBtn.button({
            emphasize: true,
            click: function (e) {
                var data = appExplorer.gtree("getSelected");
                var folderid = $("#share_directory").attr("folderid");
                var pid = $("#share_directory").attr("pid");
                var ca = {
                    "folderid": folderid,
                    "pid": pid
                }
                meunEvent.move(data, ca, '调整目录成功');
            }
        });
        $("#share_directory").on("click", function () {
            var data = appExplorer.gtree("getSelected");
            var folderid = $(this).attr("folderid");
            var pid = $(this).attr("pid");
            var ca = {
                "folderid": folderid,
                "pid": pid
            }
            meunEvent.move(data, ca, TempoUtils.locale("aiview.rsmanageMoveOK"));
        })

    }

    var getSharePath = function (appid) {
        $.ajax({
            url: contextPath + '/api/ai/app/category/path/get?t=' + TempoUtils.uuid(),
            method: 'GET',
            data: {
                id: appid
            },
            success: function (rs) {
                if (rs.success) {
                    if (rs.success) {
                        if (rs.data) {
                            $("#share_directory").text(rs.data.path).attr({
                                "title": rs.data.path,
                                "pid": rs.data.id,
                                "folderid": rs.data.parentId
                            })
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化表排序
     */
    var initTreeSortButton = function () {
        $treeSortPanel.unbind('click').bind('click', function (e) {
            configMenuOperator.showMenus(e);
        });
    }

    /**
     * 菜单的操作
     */
    var configMenuOperator = {
        /**
         * 显示菜单
         */
        showMenus: function (event) {
            var modelMenu = utils.initMenu(event, configMenuOperator.exeucteMenuFor);
            modelMenu.contextmenu('selectItem', themeTreeSort);

        },
    }
    var utils = {
        initMenu: function (event, selectCallBack, data, dealMenuStatusCallBack) {
            var modelMenu = $("<ul/>").appendTo($("body"));
            modelMenu.css({
                "z-index": 1000
            });
            var menuData = utils.getMenusData();
            modelMenu.contextmenu({
                data: menuData,
                show: true,
                selectable: true,
                select: function (e, ui) {
                    var d = ui.linkEl.data;
                    var menuId = ui.select.id;
                    var data = {
                        id: "-1",
                        sort: menuId,
                    };
                    themeTreeSort = menuId;
                    var words = $searchBar.searchbar("getValue").trim() || ""
                    switch (menuId) {
                        // 文件夹
                        case "DEFAULT" :
                            initExplorer(words);
                            break;
                        case "ASC" :
                            initExplorer(words);
                            break;
                        case "DESC" :
                            initExplorer(words);
                            break;
                    }
                    disableBtn();
                },
                close: function () {
                    modelMenu.remove();
                }
            });
            if (dealMenuStatusCallBack) {
                dealMenuStatusCallBack.call(modelMenu, data);
            }
            var posiLeft = event.pageX - 16;
            var posiTop = event.pageY + 16;
            var screenHeight = window.innerHeight;
            var minus = screenHeight - event.pageY;
            var menuHeight = modelMenu.height();
            if (minus < menuHeight) {
                posiTop = posiTop - menuHeight;
            }

            modelMenu.contextmenu("show", {
                position: {
                    left: posiLeft,
                    top: posiTop
                },
                linkEl: this
            });
            return modelMenu;
        },
        /**
         * 获取菜单数据
         */
        getMenusData: function () {
            var menuData = [{
                text: '默认排序',
                id: 'DEFAULT'
            }, {
                text: '名称顺序',
                id: 'ASC'
            }, {
                text: '名称倒序',
                id: 'DESC'
            }]
            return menuData;
        },
    }


    //加载左侧树
    var initExplorer = function (text) {
        appExplorer = $("<div>").appendTo($('.app-explorer').empty()).gtree({
            rootData: {},
            url: contextPath + '/api/ai/app/category/warehouse/listorgray',
            enableSelect: true,
            idKey: 'uuid',
            beforeRequest: function (data, e) {
                if (!text || text == "" || (data.id && data.id != '-1')) {
                    if (!data || !data.id) {
                        return {sort: themeTreeSort, name: ''};
                    } else {
                        return {sort: themeTreeSort, id: data.id};
                    }
                } else {
                    if (!data || !data.id) {
                        return {sort: themeTreeSort, name: text};
                    } else {
                        return {sort: themeTreeSort, id: data.id, name: text};
                    }
                }
            },
            beforeHover: function (data) {
                return true;
            },
            getItemIcon: function (nodeData) {
                if (nodeData.ctype === "gray") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-gray";
                } else if (nodeData.type === "sync") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-sync";
                }
                if (nodeData.ctype == 'task') {
                    return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-task';
                } else if (nodeData.fileType == 'FILE' && nodeData.ctype == "stream") {
                    return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-stream';
                } else if (nodeData.fileType == 'FILE' && nodeData.ctype == "sync") {
                    return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-sync';
                } else if (nodeData.fileType == 'FILE' && nodeData.ctype == "async") {
                    return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-async';
                } else {
                    return 'tempo-ui-icon-api-folder-close';
                }
            },
            getFolderCloseIcon: function (nodeData) {
                if (nodeData.type === "gray") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-gray";
                }
                if (nodeData.fileType == 'FILE' && nodeData.ctype == "async") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-async";
                }
                return "tempo-ui-icon-api-folder-close";
            },
            getFolderOpenIcon: function (nodeData) {
                if (nodeData.type === "gray") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-gray";
                }
                if (nodeData.fileType == 'FILE' && nodeData.ctype == "async") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-async";
                }
                return "tempo-ui-icon-api-folder-open";
            },

            onSelect: function (nodeData) {
                $rightGrayView.hide();
                var item = $(this);
                var that = $(".tempo-gtree");
                if (that.find(".tempo-icon-select").length > 0) {
                    that.find(".tempo-icon-select").removeClass("tempo-api-icon-tree-16-position-9-selected");
                    that.find(".tempo-icon-select").removeClass("tempo-api-icon-tree-16-position-10-selected")
                    that.find(".tempo-icon-select").removeClass("tempo-ui-icon-api-folder-open-selected")
                    that.find(".tempo-icon-select").removeClass("tempo-ui-icon-api-folder-close-selected");
                    that.find(".tempo-icon-select").removeClass("tempo-ai-api-icon-tree-16-position-8-selected");
                    that.find(".tempo-icon-select").removeClass("tempo-icon-select");
                }
                ;
                if (that.find(".tempo-gray-icon").length > 0) {
                    that.find(".tempo-gray-icon").removeClass("tempo-api-icon-tree-16-position-gray-select");
                }

                if (nodeData.ctype == "gray") {
                    item.find("span:eq(0)").addClass("tempo-gray-icon");
                    item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-gray-select");
                }
                if (nodeData.fileType == "FILE" || nodeData.fileType == "GFILE") {
                    // item.find("span:eq(0)").addClass("tempo-ai-api-icon-tree-16-position-8-selected");
                    item.find("span:eq(0)").addClass("tempo-icon-select");
                }
                if (nodeData.fileType == "THEME") {
                    if (item.find("span:eq(0)").hasClass("tempo-api-icon-16-tree-position-9")) {
                        item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-10-selected");
                        item.find("span:eq(0)").addClass("tempo-icon-select");
                    } else {
                        item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-9-selected");
                        item.find("span:eq(0)").addClass("tempo-icon-select");
                    }

                }
                ;
                if (nodeData.fileType == 'FOLDER' || nodeData.fileType == null) {
                    if (item.find("span:eq(0)").hasClass("tempo-ui-icon-api-folder-close")) {
                        item.find("span:eq(0)").addClass("tempo-icon-select");
                        item.find("span:eq(0)").addClass("tempo-ui-icon-api-folder-open-selected");
                    } else {
                        item.find("span:eq(0)").addClass("tempo-icon-select");
                        item.find("span:eq(0)").addClass("tempo-ui-icon-api-folder-close-selected");
                    }
                }

                if (nodeData.fileType == 'FOLDER' || nodeData.id == '-1') {
                    indexOpts.show();
                    if (nodeData.id == '-1') {
                        indexOpts_addApp.addClass('ui-state-disabled');
                    } else {
                        indexOpts_addApp.removeClass('ui-state-disabled');
                    }
                    contentOpts.hide();
                    $rightTaskView.hide();
                    var index = appExplorer.gtree('getNodeLevel', nodeData.id)
                    if (index >= 2) {
                        indexOpts_addFolder.addClass('ui-state-disabled');
                    } else {
                        indexOpts_addFolder.removeClass('ui-state-disabled');
                    }
                }
                if (nodeData.fileType == 'FILE' && nodeData.ctype == "async") {
                    appExplorer.gtree('option', 'onItemClick').call(this, nodeData);
                    $('.create-task-btn').show();
                } else {
                    $('.create-task-btn').hide();
                }
            },
            nodeButtons: [{
                isShowNodeButtons: function (data) {
                    if (data.type === 'sync') {
                        return false;
                    }
                    return data.ctype != 'task';
                },
                click: function (data, e) {
                    var $this = $(this);
                    var offset = $this.offset();

                    var seleMenuList = MenuEventInit.beforeMenuShow(data, e);
                    var popMenu = [];
                    MenuEventInit.menus.forEach(function (v) {
                        if (seleMenuList.indexOf(v.id) > -1) {
                            popMenu.push(v);
                        }
                    })
                    $('#rs_manage_context').remove();
                    var contextMenu = $("<ul id='rs_manage_context'/>").appendTo($("body")).contextmenu({
                        data: popMenu,
                        select: function (e, ui) {
                            var id = ui.select.id;
                            var linkEl = ui.linkEl;
                            if (linkEl) {
                                meunEvent[id](linkEl.data);
                            }
                        }
                    });
                    var top = offset.top;
                    var menuHeight = contextMenu.outerHeight();
                    if (top + menuHeight > window.innerHeight) {
                        top = top - menuHeight;
                    }
                    contextMenu.contextmenu("show", {
                        position: {
                            left: offset.left + $this.width() / 2 + 7,
                            top: top
                        },
                        linkEl: {
                            data: data
                        }
                    })
                }
            }],
            isLeafNode: function (nodeData) {
                if (nodeData.fileType == "GFILE" || nodeData.type == "sync") {
                    return true;
                }
                return nodeData.fileType == 'FILE' && nodeData.ctype != "async";
            },
            onItemClick: function (data, item, value) {
                if (data.ctype === "gray") {
                    var that = appExplorer.data("tempo-gtree");
                    var icon = item.find(".tempo-gtree-item-content-icon");
                    var isComplete = item.hasClass("tempo-gtree-item-complete");
                    // 标识当前文件夹是打开状态
                    var openClass = "tempo-gtree-open-folder-flag";
                    var openIcon = that.options.getFolderOpenIcon(data);
                    var closeIcon = that.options.getFolderCloseIcon(data);
                    if (isComplete) {
                        var open = icon.hasClass(openClass);
                        if (open) {
                            // 文件夹收起
                            icon.removeClass(openClass).removeClass(openIcon).addClass(closeIcon);
                            var children = item.next();
                            if (children.hasClass("tempo-gtree-childrens")) {
                                children.hide();
                            }
                        } else {
                            // 文件夹展开
                            icon.addClass(openClass).removeClass(closeIcon).addClass(openIcon);
                            var children = item.next();
                            if (children.hasClass("tempo-gtree-childrens")) {
                                children.show();
                            }
                        }
                    } else {
                        if (icon.hasClass("tempo-gtree-loading")) {
                            return;
                        }
                        icon.removeClass(closeIcon).addClass("tempo-gtree-loading");
                        that._loadData(data, function (d) {
                            var childrens = $("<div>").addClass("tempo-gtree-childrens");
                            that._render(d, childrens, parseInt(item.attr("_level")) + 1);
                            item.after(childrens.show()).addClass("tempo-gtree-item-complete");
                            icon.addClass(openClass).removeClass('tempo-gtree-loading').addClass(openIcon);
                            if (value != null && value != "") {
                                //展开二级文件夹并选中应用
                                if (value.id) {
                                    var fitem = this._getItem(value.parentId);
                                    fitem.trigger("click", value.id);
                                } else {
                                    that.clickItem(value);
                                }
                            }
                        });
                    }
                }
                openApp(data);
            },
            renderComplete: function () {
                appExplorer.gtree("expand", "-1");
            }
        });
    };
    //成果管理左侧菜单事件rename createFolder OK了  delete ok  下架ok 退回ok  移动ok  上架  ok
    //对于文件夹本身的子文件数目的4个开放字段，后台是正确的，前台不是
    var meunEvent = {
        //需要开发文件夹面板选择上架
        add: function (data) {
            $m.loadHtml(contextPath + "/api/ai/app/view/add-achievement", $('body'), 'tempo-app-add-achievement-dialog', {
                callback: addApp,
                parentId: data.id
            });
        },
        pull: function (data) {
            $.post(contextPath + "/api/ai/app/service/pull", {"id": data.id},
                function (rs) {
                    if (rs.success) {
                        appExplorer.gtree("removeItem", data.id);
                        if (appExplorer.gtree("getItem", rs.data.dataFold.id).length == 0) {
                            appExplorer.gtree("addItem", rs.data.dataFold, "unsort");
                        }
                        rs.data.dataLeaf.userName = data.userName;
                        appExplorer.gtree("addItem", rs.data.dataLeaf, rs.data.dataFold.id);
                        TempoUtils.showTip(TempoUtils.locale("aiview.rsmanagePullOk"));
                    } else {
                        if (rs.message) {
                            TempoUtils.showTip(rs.message);
                        } else {
                            TempoUtils.showTip(TempoUtils.locale("aiview.rsmanagePullError"));
                        }

                    }
                });
        },
        rename: function (data) {
            MenuEventInit.initDialog(TempoUtils.locale("aiview.rsmanageRename"), null, data.name, {
                T: TempoUtils.locale("aiview.rsmanageRenameOK"),
                F: TempoUtils.locale("aiview.rsmanageRenameError")
            }, "/api/ai/app/category/rename", {id: data.id}, function (pa) {
                appExplorer.gtree('updateItemName', data.id, pa.name);
                //更新路径名称
                if ($("#share_directory").length > 0) {
                    var appItem = appExplorer.gtree("getSelected");
                    getSharePath(appItem.id);
                }
            })
        },
        createFolder: function (data) {
            var parentId = data.id;
            if (data.id == "-1") {
                parentId = "-1";
            }

            MenuEventInit.initDialog(
                TempoUtils.locale("aiview.rsmanageCreateFolder"),
                TempoUtils.locale("aiview.rsmanageInputFolder"),
                null,
                {
                    T: TempoUtils.locale("aiview.rsmanageCreateFolderOK"),
                    F: TempoUtils.locale("aiview.rsmanageCreateFolderError")
                },
                "/api/ai/app/category/create",
                {parentId: parentId},
                function (pa, result) {
                    result.uuid = result.id;
                    appExplorer.gtree("addItem", result, parentId);
                },
                function (textareaObj) {
                    $.ajax({
                        url: contextPath + '/api/ai/app/folder/list-name',
                        method: 'post',
                        data: {
                            parentId: parentId,
                            prefix: "文件夹"
                        },
                        success: function (result) {
                            textareaObj.val(result.data);
                        }
                    });

                })
        },

        deleteFolder: function (data) {
            $('<div/>').confirm({
                msg: TempoUtils.locale("aiview.deletetip"),
                ok: function () {
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.post(contextPath + "/api/ai/app/category/delete", {"id": data.id}, function (rs) {
                        progressbar.tempoprogressbar("destroy");
                        if (rs.success) {
                            data.uuid = data.id;
                            appExplorer.gtree("removeItem", data.uuid);
                            TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageDeleteOK"));
                            appExplorer.gtree("selectItem", data.parentId);
                        } else {
                            TempoUtils.showTip(rs.message);
                        }
                    });
                }
            });
        },
        move: function (data, ca, showTip) {
            MenuEventInit.initTree(data, function (callBack, dialog) {
                $.ajax({
                    url: contextPath + '/api/ai/app/category/move',
                    method: 'POST',
                    data: {
                        id: callBack.id,
                        parentId: callBack.pid
                    },
                    success: function (rs) {
                        dialog.dialog("destroy").remove();
                        if (rs.success) {
                            var pid = callBack.pid;
                            appExplorer.gtree("removeItem", data.id);
                            data.parentId = callBack.pid;
                            appExplorer.gtree("loadAndSelectItem", data, pid);
                            TempoUtils.showTip(showTip || TempoUtils.locale("aiview.rsmanageMoveOK"));
                        } else {
                            TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageMoveError"));
                        }
                    }
                })
            }, ca);

        },
        "delete": function (data) {
            $('<div/>').confirm({
                msg: TempoUtils.locale("aiview.rsmanageRemoveMsg"),
                ok: function () {
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.post(contextPath + "/api/ai/app/category/delete", {
                        "id": data.id,
                        type: 'warehouse'
                    }, function (rs) {
                        progressbar.tempoprogressbar("destroy");
                        if (rs.success) {
                            appExplorer.gtree("removeItem", data.id);
                            TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageRemoveOK"));
                            appExplorer.gtree("selectItem", data.parentId);
                        } else {
                            TempoUtils.showTip(data.message);
                        }
                    });
                }
            })
        },
        createTask: function (data) {
            createTask(data);
        },
        deleteTask: function (data) {
            deleteTask(data);
        }
    }

    //成果管理左侧点击事件
    var openApp = function (data) {
        $rightGrayView.hide();
        if (data.fileType != "FILE") {
            indexOpts.hide();
            contentOpts.hide();
            $rightTaskView.hide();
            //灰度服务页面
            if (data.ctype === "gray") {
                contentOpts.find('.rs-right-bot').empty();
                $rightGrayView.show();
                GrayClickEvent.modifyInfo(data);
                GrayClickEvent.loadRigPage(data.id, true);
                return;
            }
            if (data.type === "sync") {
                //隐藏灰度服务下同步服务调整目录
                $(".tempo-strap-header-right").hide();
                indexOpts.hide();
                contentOpts.show();
                $rightGrayView.hide();
                var tag = true;
                if (data.parentId == "0") {
                    tag = false;
                }
                //查询同步服务数据结构传参
                $.ajax({
                    url: contextPath + '/api/ai/mine/gray/select-sync',
                    method: 'POST',
                    data: {
                        id: data.id
                    },
                    success: function (response) {
                        if (response) {
                            contentOpts.attr("objid", response.data.id);
                            clickEvent.modifyInfo(response.data, tag);
                            clickEvent.loadRigPage(response.data.id, tag);
                            updateStatusLoop(response.data.id, null, response.data.ctype);
                        }
                    }
                });
            }
            return;
        }
        var rsManageId = data.id;//成果分类的ID/服务的ID
        var tag = true;
        if (data.parentId == "0") {
            tag = false;
        }
        if ("task" != data.ctype) {
            indexOpts.hide();
            contentOpts.show();
            $(".tempo-strap-header-right").show();
            contentOpts.attr("objid", data.id);
            clickEvent.modifyInfo(data, tag);
            clickEvent.loadRigPage(rsManageId, tag);
        } else {
            indexOpts.hide();
            contentOpts.hide();
            contentOpts.find('.rs-right-bot').empty();
            $rightTaskView.show();
            //加载任务页面
            modifyInfo(data);
            loadTaskRightPage(data);
        }
        updateStatusLoop(data.id, null, data.ctype);
    };

    var GrayClickEvent = {
        modifyInfo: function (data) {
            var flowName = data.name;
            if (flowName.length > 33) {
                flowName = flowName.substr(0, 33) + "...";
            }
            $('.rs-right-top-gray span[id="ca-name-gray"]').text(flowName);
            $('.rs-right-top-gray span[id="ca-name-gray"]').attr('title', data.name);
            //灰度服务创建者
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-creator-name-by-id',
                method: 'POST',
                data: {
                    id: data.userId
                },
                success: function (userData) {
                    $('.rs-right-top-gray span[id="ca-creator-gray"]').text(userData.data.USER_NAME).attr("title", userData.data.USER_NAME);
                }
            });
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-workspace',
                method: 'POST',
                data: {
                    id: data.id
                },
                success: function (response) {
                    if (response.data != null) {
                        $('.rs-right-top-gray span[name="belong_workspace_gray"]').text(response.data.name).attr('title', response.data.name);
                    }
                }
            });
            var ctype = "";
            if (data.ctype == "gray") {
                ctype = "灰度";
            }
            $('.create-task-btn').hide();
            $('.rs-right-mid-gray span[id="ca-type-gray"]').text(ctype);
            $('.tempo-app-content-view-gray span[id="ca-time-gray"]').text(TempoUtils.locale("aidsview.published_in") +
                formatCreateTime(data.createTime));
            $rightGrayView.attr("objid", data.id);
            getSharePath(data.id)
        },
        loadRigPage: function (rsManageId, tag) {
            if (!tag) {
                $('.rs-right-mid-gray li.unsort').hide();
            } else {
                $('.rs-right-mid-gray li.unsort').show();
            }
            $('.rs-right-mid-gray').off('click').on('click', "li", function (e) {
                var vurl = $(e.target).data("v");
                $(this).siblings().removeClass("rs-right-mid-select");
                $(this).addClass("rs-right-mid-select");
                if (vurl == null) {
                    return;
                }
                $('.rs-right-bot').empty();
                if ("grayconfiguration" == vurl) {
                    $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&flag=" + true + "&&t=" + TempoUtils.uuid(), $('.service-right-bot-gray'));
                } else {
                    $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&t=" + TempoUtils.uuid(), $('.service-right-bot-gray'));
                }
            })
            $('.rs-right-mid-gray li:eq(0)').trigger('click');
        }
    };

    var information = {};
    var update = function (response) {
        var data = response.data || {};
        var resource = data.resource || {};
        var workspace = data.workspace || {};
        if (resource.name && resource.name.length > 20) {
            var trimThemeName = resource.name.substr(0, 20) + "...";
            $('.rs-right-top span[name="belong_theme"]').text(trimThemeName).attr('title', resource.name);
        } else {
            $('.rs-right-top span[name="belong_theme"]').text(resource.name).attr('title', resource.name);
        }
        if (workspace.name && workspace.name.trim()) {
            $('.rs-right-top span[name="belong_workspace"]').text(workspace.name).attr('title', workspace.name);
        } else {
            $('.rs-right-top span[name="belong_workspace"]').text(TempoUtils.locale("aiview.my_workspace"));
        }
    }
    //格式化日期 （显示为先月日）
    var formatCreateTime = function (createTime) {
        var time = DateUtils.getCountTime(DateUtils.formatDate(createTime, 'yyyy-MM-dd hh:mm:ss')).split(" ");
        var createTime = DateUtils.formatDate(createTime, 'yyyy-MM-dd');
        // if(time[0]==0&&time[1]!=0){
        //  createTime=time[1]+"小时前";
        //  }
        // if(time[0]==0&&time[1]==0){
        //  createTime=time[2]+"分钟前";
        // }
        // if(time[0]==0&&time[1]==0&&time[2]==0){
        //    createTime=1+"分钟前";
        // }
        return createTime;
    }
    var clickEvent = {
        modifyInfo: function (data, tag) {
            var flowName = data.name;
            if (flowName.length > 33) {
                flowName = flowName.substr(0, 33) + "...";
            }
            $('.rs-right-top span[id="ca-name"]').text(flowName);
            //添加同步服务标识
            var span = $($('.rs-right-top span[id="ca-name"]')[0]);
            if (data.flowType == "plflow") {
                span.next().show();
            } else {
                span.next().hide();
            }
            //灰度服务中同步服务创建者
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-creator-name-by-userid',
                method: 'POST',
                data: {
                    id: data.userId
                },
                success: function (userData) {
                    $('.rs-right-top span[id="ca-creator"]').text(userData.data.USER_NAME).attr("title", userData.data.USER_NAME);
                }
            });
            if (information[data.id]) {
                update(information[data.id]);
            } else {
                $.ajax({
                    url: contextPath + '/api/ai/app/information',
                    method: 'POST',
                    data: {
                        id: data.id
                    },
                    success: function (response) {
                        update(response);
                    }
                });
            }

            var status = "";
            var ctype = "";

            switch (data.ctype) {
                case "sync":
                    ctype = TempoUtils.locale("aiview.sync_service");
                    if (data.parentId && data.parentId == "0") {
                        status = TempoUtils.locale("aiview.status-publish");
                    } else {
                        status = MenuEventInit.getSyncStatus(data.id);
                    }
                    break;
                case "async":
                    ctype = TempoUtils.locale("aiview.async_service");
                    status = TempoUtils.locale("aiview.status-publish");
                    break;
                case "stream":
                    ctype = TempoUtils.locale("aiview.stream_service");
                    if (data.parentId && data.parentId == "0") {
                        status = TempoUtils.locale("aiview.status-publish");
                    } else {
                        status = MenuEventInit.getSyncStatus(data.id);
                    }
                    break;
            }
            $('#ca-type').text(ctype);
            if (ctype.length > 3) {
                $('#ca-type').text(ctype.substring(0, 2));
            }
            var catime = "";//catime的处理
            if (data.parentId == "0") {
                catime += TempoUtils.locale("aiview.rsmanagePubTime") + ": ";
                if (data.publishTime != null) {
                    catime += new Date(data.publishTime).Format("yyyy-MM-dd hh:mm:ss");
                } else {
                    catime += new Date(data.putTime).Format("yyyy-MM-dd");
                }
            } else {
                catime += "发布于：";
                catime += formatCreateTime(data.putTime);
            }

            $('div[objid="' + data.id + '"] #ca-status').text(status);
            $('#ca-time').text(catime);
            getSharePath(data.id)
        },
        loadRigPage: function (rsManageId, tag) {
            if (!tag) {
                $('.rs-right-mid li.unsort').hide();
            } else {
                $('.rs-right-mid li.unsort').show();
            }
            $('.rs-right-mid').off('click').on('click', "li", function (e) {
                var vurl = $(e.target).data("v");
                if (vurl == "configuration") {
                    $('.tempo-cgfl-sync-service-pl-image').css("margin-top", "-30px");
                }
                $(this).siblings().removeClass("rs-right-mid-select");
                $(this).addClass("rs-right-mid-select");
                if (vurl == null) {
                    return;
                }
                $('.rs-right-bot').empty();
                $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&t=" + TempoUtils.uuid(), $('.service-right-bot'));
            })
            $('.rs-right-mid li:eq(0)').trigger('click');
        }
    }
    //菜单点击事件中的辅助事件
    var MenuEventInit = {
        menus: [{
            text: TempoUtils.locale("aiview.menuAdd"),
            id: 'add',
        }, {
            text: TempoUtils.locale("aiview.rsmanageCreateFolder"),
            id: 'createFolder',
        }, {
            text: TempoUtils.locale("aidsview.create_new_task"),
            id: 'createTask',
        }, {
            text: TempoUtils.locale("aiview.menuMove"),
            id: 'move',
        }, {
            text: TempoUtils.locale("aiview.menuRename"),
            id: 'rename',
        }, {
            text: TempoUtils.locale("aiview.menuDel"),
            id: 'deleteFolder',
        }, {
            text: TempoUtils.locale("aiview.menuRemove"),
            id: 'delete',
        }, {
            text: TempoUtils.locale("aiview.menuRemove"),
            id: 'deleteTask',
        }],
        beforeMenuShow: function (data, ele) {
            var index = appExplorer.gtree('getNodeLevel', data.id)
            if (data && (data.ctype == 'folder' || data.id == "-1")) {
                if (data.id == "-1") {
                    return ['createFolder'];
                }
                if (index >= 2) {
                    return ['add', 'rename', 'deleteFolder'];
                }
                return ['add', 'rename', 'createFolder', 'deleteFolder'];
            } else if (data && data.ctype == 'task') {
                return [];
            } else {
                return ['move', 'delete'];
            }
            return [];
        },
        getSyncStatus: function (id) {
            var status = TempoUtils.locale("aiview.serviceUnStart");
            updateStatusLoop(id);
            return status;
        },
        initTree: function (data, callback, ca) {
            var moveTitle = TempoUtils.locale("aiview.menuMove");
            if (ca != null) {
                //调整目录
                moveTitle = TempoUtils.locale("aiview.app_select_target");
            }
            var folderid = "";
            var dialog = $("<div/>", {
                'class': 'tempo-app-achievement-move-dialog'
            });
            var content = $("<div>").addClass("tempo-strap-dialog-tree-container").appendTo(dialog);
            content.css('height', '100%');
            var $treeDiv = $("<div>").addClass("tempo-strap-dialog-tree").appendTo(content);
            $treeDiv.css('width', ' calc(100% - 35px)');
            dialog.dialog({
                modal: true,
                width: 500,
                height: 400,
                resizable: false,
                title: moveTitle,
                open: function () {
                    $.ajax({
                        url: contextPath + '/api/ai/app/category/tree',
                        method: 'POST',
                        data: {
                            id: "-1"
                        },
                        success: function (rs) {
                            if (rs.success) {
                                var rootfolder = rs.data[0];
                                var datas = rootfolder.children
                                if (datas.length > 0) {
                                    $treeDiv.gtree({
                                        data: rs.data,
                                        getItemIcon: function (nodeData) {
                                            return 'tempo-ui-icon-api-folder-close';
                                        },
                                        enableSelect: true,
                                        renderComplete: function () {
                                            $treeDiv.gtree('expand', '-1');
                                            if (ca != null) {
                                                if (ca.folderid == "-1") {
                                                    $treeDiv.gtree("clickItem", ca.pid)
                                                } else {
                                                    $treeDiv.gtree("clickItem", ca.folderid);
                                                    $treeDiv.gtree("clickItem", ca.pid)
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    // 如果没有可选文件夹，添加提示
                                    $("<div>").css({
                                        'position': 'absolute',
                                        'height': '100%',
                                        'width': 'calc(100% - 40px)',
                                        'line-height': '298px',
                                        'top': '0px',
                                        'text-align': 'center',
                                        'font-size': '14px'
                                    }).text('请先在模型仓库中中创建分类文件夹').appendTo(content);
                                }
                            } else {
                                TempoUtils.showTip(TempoUtils.locale("aiview.rsLoadErr"));
                            }
                        }
                    });
                },
                buttons: [{
                    text: TempoUtils.locale("aiview.confirm"),
                    id: "theme_operate_button",
                    click: function () {
                        try {
                            var node = $treeDiv.gtree("getSelected");
                            if (node && node.id != '-1') {
                                if (callback != null && typeof callback == "function") {
                                    callback({pid: node.id, id: data.id}, dialog);
                                }
                            } else {
                                TempoUtils.showTip(TempoUtils.locale("aiview.rsSelFol"));
                            }
                        } catch (e) {
                            dialog.dialog("destroy").remove();
                        }
                    }
                }, {
                    text: TempoUtils.locale("aiview.cancel"),
                    id: "theme_operate_button",
                    click: function () {
                        dialog.dialog("destroy").remove();
                    }
                }],
                close: function () {
                    // 销毁弹出框,并返回
                    dialog.dialog("destroy").remove();
                }
            });
        },
        initDialog: function (title, placeholder, initName, showTips, addr, params, callBack, callBack2) {
            var paramDialog = $('<div class="tempo-rs-operate" style="text-align:center;width:100%;height:100%;"/></div>').appendTo($('body'));
            var renameDiv = $('<div id="rename-category">').appendTo(paramDialog);
            if (placeholder == null) {
                placeholder = "";
            }
            if (addr.indexOf("decline") > -1) {
                $("<label class='theme_operate_input_name'>" + TempoUtils.locale("aiview.descript") + "</label>").appendTo(renameDiv);
            } else {
                $("<label class='theme_operate_input_name'>" + TempoUtils.locale("aiview.name") + "</label>").appendTo(renameDiv);
            }
            var textArea = $('<input id="rename-category-textarea"></input>').addClass("tempo-validatebox").appendTo(renameDiv);
            paramDialog.dialog({
                title: title,
                autoOpen: true,
                width: 500,
                height: 197,
                resizable: false,
                modal: true,
                close: function () {
                    paramDialog.find("#rename-category").empty();
                    paramDialog.dialog('destroy');
                    paramDialog.remove();
                },
                open: function () {
                    textArea.validatebox({
                        //模型仓库新建文件夹命名校验可以使用特殊字符命名
                        //valids:[/^[^~!@#\$%\^&\*\+\[\]\|\}\{\\;':",\.\/<>\?`]+$/],
                        tip: TempoUtils.locale("resource.name_valid_tip"),
                        required: true,
                        maxLength: 60,
                        autofill: false
                    });
                    if (initName != null) {
                        textArea.val(initName);
                    }
                    if (callBack2) {
                        callBack2(textArea);
                    }
                },
                buttons: [
                    {
                        text: TempoUtils.locale("aiview.confirm"),
                        id: "theme_operate_button",
                        click: function () {
                            if (!paramDialog.find("#rename-category-textarea").validatebox("doValidate")) {
                                return false;
                            }
                            var reqParams = {name: paramDialog.find("#rename-category-textarea").val()};
                            if (addr.indexOf("decline") > -1) {//backcomment退回说明字段
                                reqParams = {backComment: paramDialog.find("#rename-category-textarea").val()};
                            }
                            var progressbar = $("<div/>").tempoprogressbar();
                            $.post(contextPath + addr, $.extend(params, reqParams),
                                function (rs) {
                                    progressbar.tempoprogressbar("destroy");
                                    if (rs.success) {
                                        paramDialog.dialog('destroy');
                                        paramDialog.remove();
                                        callBack({name: paramDialog.find("#rename-category-textarea").val()}, rs.data);
                                        //TempoUtils.showTip(showTips["T"]);
                                    } else {
                                        if (rs.message != null && rs.message != "") {
                                            TempoUtils.showTip(rs.message);
                                        } else {
                                            TempoUtils.showTip(showTips["F"]);
                                        }
                                    }

                                });

                        }
                    },
                    {
                        text: TempoUtils.locale("aiview.cancel"),
                        id: "theme_operate_button",
                        click: function () {
                            paramDialog.dialog('destroy');
                            paramDialog.remove();
                        }
                    }
                ]
            });
        }
    }

    var deleteEmptyTheme = function (themeid) {
        //主题下为空，则删除主题
        var parentData = {id: themeid}
        var childrenLength = appExplorer.gtree("getChildren", parentData).length;
        if (childrenLength == 0) {
            appExplorer.gtree("removeItem", themeid);
        }
    }

    /**
     * 添加成果
     */
    var addApp = function (parentId, apps, result) {
        if (result.success) {
            // 添加到左侧树上
            for (var d in result.data) {
                result.data[d].uuid = result.data[d].id;
                appExplorer.gtree("addItem", result.data[d], parentId);
            }
            TempoUtils.showTip(TempoUtils.locale("aiview.addSuccess"));
        } else {
            TempoUtils.showTip(TempoUtils.locale("aiview.addFailed"));
        }
    }

    /**
     * 创建任务
     */
    var createTask = function (data) {
        $m.loadHtml(contextPath + "/api/ai/view/load/app-single-task-dialog", $('body'), 'tempo-app-add-task-dialog', {
            callback: function (task, job) {
                var leaf = {};
                var leaf = {};
                var trigger = job.trigger;
                leaf.id = job.id;
                leaf.name = trigger.name;
                leaf.type = 'task';
                leaf.fileType = 'FILE';
                leaf.parentId = data.id;
                leaf.fileType = 'FILE';
                leaf.ctype = 'task';
                appExplorer.gtree("addItem", leaf, data.id);
            },
            data: data
        });
    }

    var deleteTask = function (data) {
        var id = data.id;
        $('<div/>').confirm({
            msg: '是否移除该任务？',
            ok: function () {
                var progressbar = $("<div/>").tempoprogressbar();
                $.post(contextPath + "/api/ai/app/schedule/info", {"id": id}, function (info) {
                    if (info.data) {
                        var jobinfo = info.data;
                        var triggerid = jobinfo.jobId;
                        $.post(contextPath + "/api/ai/app/schedule/job/delete", {
                            "id": id,
                            "triggerId": triggerid
                        }, function (rs) {
                            progressbar.tempoprogressbar("destroy");
                            if (rs.success) {
                                appExplorer.gtree("removeItem", id);
                                TempoUtils.showTip(TempoUtils.locale("aiview.rsmanageDeleteOK"));
                                appExplorer.gtree("selectItem", data.parentId);
                            } else {
                                TempoUtils.showTip(rs.message);
                            }
                        });
                    } else {
                        progressbar.tempoprogressbar("destroy");
                        TempoUtils.showTip(info.message);
                    }
                });
            }
        })
    }

    var validateForm = function (dialog, isEdit) {
        var v = dialog.find('form').formValidate();
        var jobconfig = TempoUtils.getRecord(dialog.find('form'));
        var triggerName = jobconfig.name;
        var isRaname = false;
        $.ajax({
            url: contextPath + '/api/ai/mine/publish/listAllTriggerName',
            type: 'post',
            async: false,
            success: function (triggerNames) {
                if (triggerNames) {
                    isRaname = triggerNames.indexOf(triggerName) > -1;
                }
            }
        });
        if (isRaname) {
            $("<div/>").alert({msg: TempoUtils.locale("mine.triggernameerror"), height: 180});
            return false;
        }
        return v && (function () {
            console.log(jobconfig);
            if (jobconfig.starttime && jobconfig.endtime) {
                var s = new Date(jobconfig.starttime);
                var e = new Date(jobconfig.endtime);
                if (s.getTime() > e.getTime()) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.shengxiaoshijianerror"), height: 180});
                    return false;
                }
            }
            if (jobconfig.stime && jobconfig.etime) {
                if (jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.kaishishijianerror"), height: 180});
                    return false;
                }
                if (jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height: 180});
                    return false;
                }
            }
            return true;
        })();
    }

    var saveTaskConfig = function (dialog, flowInfo) {
        if (!validateForm(dialog, flowInfo)) {
            return;
        }
        var job = {
            trigger: {},
            publishFlowIds: []
        };
        var triggerParam = {};
        var trigger = job.trigger;
        var publishFlowIds = [];
        var publishFlowNames = [];
        //调度信息
        var jobconfig = dialog.find('#tempo-mine-flow-config').serializeArray();

        // 添加对复选框值的处理，转变为一个属性值
        $.each(jobconfig, function (index, item) {
            if (!item.name.startsWith('flow_')) {
                if (trigger[item.name]) {
                    if (Array.isArray(trigger[item.name])) {
                        trigger[item.name].push(item.value);
                    } else {
                        trigger[item.name] = [trigger[item.name], item.value];
                    }
                } else {
                    trigger[item.name] = item.value;
                }
            }
        });
        // 解决IE10下面选中保存不了问题
        var isChecked = dialog.find('input[name=retry]').is(':checked');
        if (!trigger.retry && isChecked) {
            trigger.retry = 'on';
        }

        if ((dialog.find('input[name=dayofweek]').length && !trigger['dayofweek'])
            || (dialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
            $("<div/>").alert({msg: TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height: 180});
            return false;
        }
        // 处理数组类型值，转换为逗号分割的字符串
        Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
        Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
        trigger['dayofweek'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
        trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
        delete trigger['dayofweek'];
        delete trigger['dayofmonth'];
        console.log(JSON.stringify(trigger))
        trigger.interval = Number(trigger.interval);
        if (trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);
        var relatedFlow = [];
        var rflowObj = {};
        rflowObj["flow_current"] = flowInfo.id;
        relatedFlow.push(rflowObj);
        triggerParam.flowsInJob = relatedFlow;
        job.publishFlowIds = flowInfo.id;
        job.publishFlowNames = flowInfo.name;
        //流程配置参数
        triggerParam.flowsParam = {};
        triggerParam.flowsParam[flowInfo.id] = getCurrentFlowParams(dialog);
        job.trigger.param = JSON.stringify(triggerParam);
        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/schedule/job/save';
        $.ajax({
            url: url,
            type: 'post',
            data: JSON.stringify(job),
            contentType: 'application/json',
            success: function (obj) {
                process.tempoprogressbar("destroy");
                if (obj && obj.data && obj.data.status) {
                    $('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    dialog.dialog("destroy");
                } else {
                    $("<div/>").alert({msg: obj.data.error, height: 180, width: 400});
                }
            },
            error: function (data) {
                process.tempoprogressbar("destroy");
            }
        });
    }

    var getCurrentFlowParams = function (dialog) {
        var paramsTable = dialog.find('#flowParamsContainer table');
        var currentFlowParams = []
        var paramsLine = paramsTable.find('tbody tr');
        paramsLine.each(function (i) {
            var paramName = $(this).find('input.flow_paramname').val();
            var paramType = $(this).find('input.flow_paramtype').val();
            var paramId = $(this).find('input.flow_paramid').val();
            var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
            var param = {};
            param.paramName = paramName;
            param.paramValue = paramValue;
            param.paramId = paramId;
            param.paramType = paramType;
            if (!$.isEmptyObject(param)) {
                currentFlowParams.push(param);
            }
        });
        return currentFlowParams;
    }

    var setFlowParams = function (dialog, flowInfo) {
        var flowid = flowInfo.id;
        dialog.find('#flowParamsContainer').hide();
        var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
        dialog.find("#publish-mine-job-param-label").text(flowInfo.name + '-' + paramLabel);
        var grid = dialog.find('#setFlowParamTable').find('tbody').empty();
        $.ajax({
            url: contextPath + "/api/ai/app/schedule/flowparams/get/" + flowid,
            type: 'post',
            success: function (result) {
                if (result && result.data && result.data.length > 0) {
                    initParamGrid(dialog, result.data);
                }
            }
        });
    }

    var getFlowParams = function (type, paramValueInput, value, nodeType) {
        var pss = [];
        if (type == 'datasource') {
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/node/io/list-datasources',
                type: 'post',
                success: function (rs) {
                    process.tempoprogressbar("destroy");
                    var data = rs.data;
                    var itemHtml = [];
                    for (var i = 0; i < data.length; i++) {
                        var dataItem = data[i];
                        // 屏蔽模型数据源、presto数据源、impala数据源
                        if (nodeType == 'readrdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                continue;
                            }
                        }
                        if (nodeType == 'writerdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        if (nodeType == 'readhive') {
                            if (dataItem.type != 'hive') {
                                continue;
                            }
                        }
                        if(nodeType == 'writehive'){
                            if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                                continue;
                            }
                        }
                        if (nodeType == "readinfluxdb") {
                            if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                continue;
                            }
                        }
                        if( nodeType == "readiotdb"){
                            if (dataItem.type != 'iotdb') {
                                continue;
                            }
                        }
                        if( nodeType == "writeiotdb"){
                            //不是iotdb  或者不能写入
                            if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }
                        itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                    }
                    var html = itemHtml.join('');
                    paramValueInput.html(html);
                    paramValueInput.selectmenu({
                        editable: false,
                        width: 150,
                        labelForTitle: true
                    }).selectmenu('setValue', value).selectmenu('refresh');
                }
            });
        } else {
            var items = TempoMineUtils.getConstFlowParams();
            if (items) {
                for (name in items) {
                    pss.push('<option value="' + name + '">' + items[name] + '</option>')
                }
            }
            var html = pss.join('');
            paramValueInput.html(html);
            paramValueInput.selectmenu({
                editable: true,
                width: 150,
                labelForTitle: true
            }).selectmenu('setValue', value);
        }

    }

    var initParamGrid = function (dialog, ps) {
        var grid = dialog.find('#setFlowParamTable');
        dialog.find('#flowParamsContainer').show();
        if (ps && ps.length > 0) {
            for (var i = 0; i < ps.length; i++) {
                var tr = $('<tr>').appendTo(grid);
                var p = ps[i];
                var paramName = p.paramName;
                var paramValue = p.paramValue;
                var paramType = p.paramType;
                var paramId = p.paramId;
                var nodeType = p.nodeType;
                var paramNameTd = $('<td>').appendTo(tr);
                var paramNameInput = $('<input name="paramName">')
                    .addClass('flow_paramname')
                    .appendTo(paramNameTd)
                    .val(paramName);
                var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
                var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
                var paramValueTd = $('<td>').appendTo(tr);
                var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
                paramNameInput.validatebox({width: 100, readonly: true});

                paramNameInput.attr('title', paramName);
                getFlowParams(paramType, paramValueInput, paramValue, nodeType);
            }
        }
    };

    var initFormData = function (dialog) {
        TempoUtils.parserUi(dialog, {});
        dialog.find('input[name="retry"]').checkbox({
            change: function (e, ui) {
                console.log(e, ui);
                if (ui.checked) {
                    dialog.find('input[name="retryNum"]').numberbox({disabled: false, required: true});
                } else {
                    dialog.find('input[name="retryNum"]').numberbox({disabled: true, required: false});
                }
            }
        });

        dialog.find('.datefield').datepicker({
            dateFormat: 'yy-mm-dd',
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        });
        dialog.find('.timefield').timepicker({
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            timeInput: true
        });

        var internalInput = dialog.find('input[name=interval]');
        dialog.find('select[name="triggertype"]').selectmenu({
            selectFirst: false,
            change: function (e, ui) {
                console.log(e, ui);
                changeTriggerType(ui.item.value);
            }
        });

        var changeTriggerType = function (value) {
            if (value == "-2") {
                //分钟
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
                internalInput.numberbox({max: 59, min: 1}).val(30);
            } else if (value == "-1") {
                //小时
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
                internalInput.numberbox({max: 23, min: 1}).val(3);
            } else if (value == "0") {
                //天
                switchShowItem(dialog, false, false, true, true, 3);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
                internalInput.numberbox({max: 31, min: 1}).val(1);
            } else if (value == "1") {
                //周
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
                switchShowItem(dialog, true, false, true, false);
                buildWeeks(dialog);
                internalInput.numberbox({max: 6, min: 1}).val(1);
            } else if (value == "2") {
                //月
                switchShowItem(dialog, true, false, true, true, 2);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
                buildDays(dialog);
                internalInput.numberbox({max: 11, min: 1}).val(1);
            }
        }

        dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
        changeTriggerType(0);
        dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
    }

    /**
     * 调度时间切换方法
     */
    var switchShowItem = function (dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
        var _onoff = $.fn.onoff;
        $.fn.onoff = function (value) {
            var element = $(this);
            if (value) {
                element.show();
            } else {
                element.hide();
            }
            element.find('input').each(function (index, ele) {
                var role = $(ele).attr('ui-role');
                if (role == 'validatebox' || role == 'numberbox') {
                    !value ? $(ele)[role]('disable') : $(ele)[role]('enable');
                }
            });
        }
        dialog.find('.times-row').onoff(timesRow);
        dialog.find('.times-board').empty();
        if (timeRange) {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: true}).validatebox('validate');
        } else {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: false}).validatebox('validate');
        }
        dialog.find('.day-of-time-range-row').onoff(timeRange);
        dialog.find('.day-of-time-row').onoff(dayTime);
        dialog.find('.time-interval-row').onoff(interval);
        if (interval && dayMonthYear != undefined) {
            dialog.find('.time-of-day').onoff(dayMonthYear == 1);
            dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
            dialog.find('.day-of-month').onoff(dayMonthYear == 2);
            dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
            dialog.find('.month-of-year').onoff(dayMonthYear == 3);
            dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
        }
        $.fn.onoff = _onoff;
    }

    /**
     * 构建周页面
     */
    var buildWeeks = function (dialog) {
        var board = dialog.find('.times-board');
        var weeks = [2, 3, 4, 5, 6, 7, 1];
        var weekName = [TempoUtils.locale("mine.xinqiyi"),
            TempoUtils.locale("mine.xinqier"),
            TempoUtils.locale("mine.xinqisan"),
            TempoUtils.locale("mine.xinqisi"),
            TempoUtils.locale("mine.xinqiwu"),
            TempoUtils.locale("mine.xinqiliu"),
            TempoUtils.locale("mine.xinqitian")
        ];
        weeks.forEach(function (e, i) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
            $("<label/>").text(weekName[i]).appendTo(span);
        });
        TempoUtils.parserUi(board, {});
    };

    /**
     * 构建天页面
     */
    var buildDays = function (dialog) {
        var board = dialog.find('.times-board');
        for (var i = 1; i <= 31; i++) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
                .val(i)
                .addClass('day-of-month-' + i)
                .appendTo(span);
            $("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
        }
        var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
        $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
            .val("L")
            .addClass('day-of-month-L')
            .appendTo(lastSpan);
        $("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
        TempoUtils.parserUi(board, {});
    }

    var modifyInfo = function (data) {
        $('.rs-right-top span[id="task-creator"]').text(data.userName).attr("title", data.userName);
        var catime = new Date(data.createTime).Format("yyyy-MM-dd hh:mm:ss");
        $('.rs-right-top span[id="task-time"]').text(catime);
        $.ajax({
            url: contextPath + '/api/ai/mine/publish/listJobInfo',
            type: 'post',
            dataType: 'json',
            data: {
                id: data.id
            },
            success: function (result) {
                if ("true" == result.flag) {
                    var job = result.job;
                    var taskStatusDesc = "生效";
                    if (job.trigger.status == "PAUSED" || job.trigger.status == "PAUSED_BLOCKED") {
                        taskStatusDesc = '暂停';
                    } else if (job.trigger.status == "COMPLETE") {
                        taskStatusDesc = '失效';
                    } else if (job.trigger.status == "AWAIT") {
                        taskStatusDesc = '等待';
                    }

                    $('.rs-right-top span[id="task-createTime"]').text(formatCreateTime(job.createTime));
                    $('.rs-right-mid span[class="task-runtStatus"]').text(taskStatusDesc).attr("id", job.id);
                    $('.tempo-app-task-view span[id="ca-name"]').text(job.trigger.name);
                }
            }
        });
        if (information[data.id]) {
            update(information[data.id]);
        } else {
            $.ajax({
                url: contextPath + '/api/ai/app/information',
                method: 'POST',
                data: {
                    id: data.parentId
                },
                success: function (response) {
                    update(response);
                }
            });
        }
    }

    var loadTaskRightPage = function (data) {
        $('.task-right-bot li.unsort').show();
        $('.task-right-mid').off('click').on('click', "li", function (e) {
            var vurl = $(e.target).data("v");
            $(this).siblings().removeClass("rs-right-mid-select");
            $(this).addClass("rs-right-mid-select");
            if (vurl == null) {
                return;
            }
            $('.task-right-bot').empty();
            var id = data.id;
            if ("overview" == vurl) {
                id = data.parentId;
            }
            $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + id + "&&t=" + TempoUtils.uuid() + "&&serviceId=" + data.parentId, $('.task-right-bot'));
        })
        $('.task-right-mid li:eq(0)').trigger('click');
    }
    // 请求服务状态
    var isAlive = function (fn, uid) {
        var id = uid || row.id
        $.postForm({
            url: contextPath + '/api/ai/app/model/status/' + id,
            success: function (rp) {
                fn(rp.data == 'STARTING' || rp.data == 'RUNNING', rp.data);
            }
        });
    }
    var updateStatusLoop = function (id, updateFn, type) {
        if (type != 'sync' && type != 'stream') {
            window.loopUpdateTimer = -1;
            return;
        }
        var timer = setTimeout(function () {
            var fn = arguments.callee;
            isAlive(function (d, status) {
                if (window.loopUpdateTimer != timer) {
                    return;
                }
                if (status == 'STARTING') {
                    serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    timer = setTimeout(fn, 1000);
                    window.loopUpdateTimer = timer
                } else if (status == 'RUNNING') {
                    if (typeof row != "undefined") row.launchState = status;
                    $('div[objid="' + id + '"] a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
                    $("div[objid='" + id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceHasStart"));
                    serviceStatus = TempoUtils.locale("aiview.serviceHasStart");
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    $('div[objid="' + id + '"] a.start-button').removeClass("ui-state-disabled");
                    if (updateFn) updateFn();
                } else {
                    $('div[objid="' + id + '"] a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                    $("div[objid='" + id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceUnStart"));
                    serviceStatus = TempoUtils.locale("aiview.serviceUnStart");
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    $('div[objid="' + id + '"] a.start-button').removeClass("ui-state-disabled");
                    if (updateFn) updateFn();
                }
            }, id);
        });
        window.loopUpdateTimer = timer;
    }

    var updateGTreeDataById = function (id) {
        appExplorer.gtree("reloadItem", id);
    }
    Eventbus.bind('updateStatusLoop.service', updateStatusLoop);
    Eventbus.one('updateGTreeDataById.service', updateGTreeDataById);
    initExplorer();
    initTreeSortButton();
    bindIndexEvents();
});